/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.domain;

import com.google.inject.Inject;
import com.google.inject.Provider;
import org.xptracker.persistence.Identified;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class DomainUtil {
  @Inject
  private static Provider<Domain> domain;

  @SuppressWarnings({"unchecked"})
  public static <T extends Identified> T fullyLoad(T item) {
    if (item != null) {
      return (T) domain.get().loadEntity(item.getClass(), item.getId());
    }
    return null;
  }

  public static <T extends Identified> List<T> fullyLoadItems(List<T> stories) {
    List<T> reloadedStories = new ArrayList<T>(stories.size());
    for(T s: stories) {
      reloadedStories.add(fullyLoad(s));
    }
    return reloadedStories;
  }

  public static Story loadStory(Long storyId) {
    return domain.get().loadEntity(Story.class, String.valueOf(storyId));
  }

  public static Map<String, List<StoryCategory>> makeCategoryMap(List<StoryCategory> categoryList) {
    Map<String, List<StoryCategory>> categoryMap =  new TreeMap<String, List<StoryCategory>>();
    for(StoryCategory category: categoryList) {
      String type = category.getType();
      type = (type == null ? "" : type);
      List<StoryCategory> categories = categoryMap.get(type);
      if (categories == null) {
        categories = new ArrayList<StoryCategory>();
        categoryMap.put(type, categories);
      }
      categories.add(category);
    }
    return categoryMap;
  }
}
